use crate::{config::DBClient, models::User};

impl DBClient {
    pub async fn save_user(&self, email: &str, password: &str) -> Result<User, sqlx::Error> {
        let id = uuid::Uuid::new_v4().to_string();

        let create_at = chrono::Local::now();

        let user = sqlx::query_as!(
            User,
            r#"
            insert into users(id, email, password, create_at)
            values(?,?,?,?)
            returning id, email, password, create_at, update_at
            "#,
            id,
            email,
            password,
            create_at,
        )
        .fetch_one(&self.pool)
        .await?;

        Ok(user)
    }

    pub async fn get_user_by_id(&self, id: &str) -> Result<Option<User>, sqlx::Error> {
        let user = sqlx::query_as!(
            User,
            r#"
            select id, email, password, create_at, update_at from users where id = ?
            "#,
            id
        )
        .fetch_optional(&self.pool)
        .await?;

        Ok(user)
    }

    pub async fn get_user_by_email(&self, email: &str) -> Result<Option<User>, sqlx::Error> {
        let user = sqlx::query_as!(
            User,
            r#"
            select id, email, password, create_at, update_at from users where email = ?
            "#,
            email
        )
        .fetch_optional(&self.pool)
        .await?;

        Ok(user)
    }
}
